package com.example.springdesignpattern.strategy.listener;

import com.example.springdesignpattern.strategy.MsgServiceContext;
import com.example.springdesignpattern.strategy.service.MsgHandleService;
import com.example.springdesignpattern.strategy.util.MSG_TYPE;
import com.example.springdesignpattern.strategy.util.MsgHandler;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MsgListener implements ApplicationListener<ContextRefreshedEvent> {

  @Override
  public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
    Map<String, Object> beans =
        contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(MsgHandler.class);
    MsgServiceContext msgServiceContext =
        contextRefreshedEvent.getApplicationContext().getBean(MsgServiceContext.class);
    for (Map.Entry<String, Object> entry : beans.entrySet()) {
      // 遍历消息处理器
      MsgHandler msgHandler = entry.getValue().getClass().getAnnotation(MsgHandler.class);
      msgServiceContext.putMsgHandleService(
          msgHandler.value().code, (MsgHandleService) entry.getValue());
    }
  }
}
